/**
 * Copyright (c) 2017-2020 四川智慧云天 All rights reserved.
 *
 * https://www.sczhyt.cn
 *
 * 版权所有，侵权必究！
 */

package cn.sczhyt.modules.app.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.sczhyt.common.exception.RRException;
import cn.sczhyt.modules.app.dao.UserDao;
import cn.sczhyt.modules.app.entity.UserEntity;
import cn.sczhyt.modules.app.form.LoginForm;
import cn.sczhyt.modules.app.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.stereotype.Service;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

	@Override
	public UserEntity queryByMobile(String mobile) {
		return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("mobile", mobile));
	}

	@Override
	public UserEntity queryByUsername(String username) {
		return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("username", username));
	}

	@Override
	public UserEntity login(LoginForm form) {
		if (form.getUsername() != null || form.getMobile() != null){
			if (form.getMobile() != null) {
				UserEntity user = queryByMobile(form.getMobile());

				//用户不存在
				if(user == null ){
					throw new RRException("用户不存在！",201);
				}
				//密码错误
				if(!user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())){
					throw new RRException("手机号或密码错误",202);
				}
				//账户无登录APP权限
				if(user.getStatusApp()!=1){
					throw  new RRException("账号已被锁定,请联系管理员！",203);
				}

				return user;
			}
			if (form.getUsername() != null) {
				UserEntity user = queryByUsername(form.getUsername());
				//账户不存在
				if(user == null ){
					throw new RRException("账户不存在！",201);
				}
				//密码错误
				if(!user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())){
					throw new RRException("用户名或密码错误",202);
				}
				//账户不存在
				if(user.getStatusApp()!=1){
					throw new RRException("账户已被锁定,请联系管理员!",203);
				}

				return user;
			}
		}

		throw new RRException("请输入用户名或者手机号");
	}


}
